import { login, logout, getInfo } from '@/api/modules/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, constantRoutes,asyncRoutes ,anyRoutes} from '@/router'
import router from '@/router'

// 引入深拷贝
import { cloneDeep } from 'lodash'
// 过滤异步路由
const filterAsyncRoutes = function (originAsyncRoutes, localAsyncRoutes) {
  // 深拷贝
  const cloneLocalAsyncRoutes = cloneDeep(localAsyncRoutes)

  return cloneLocalAsyncRoutes.filter((localItem) => {
    if (originAsyncRoutes.find(originItem => originItem === localItem.name)) {
      if (localItem.children && localItem.children.length > 0) {
        localItem.children = filterAsyncRoutes(originAsyncRoutes, localItem.children)
      }
      return true
    }
  })
}

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',

    // 权限相关
    // 用户能看见的总路由
    routes: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, { name, avatar }) => {
    state.name = name
    state.avatar = avatar
  },
  // 设置异步路由
  SET_ASYNCROUTES(state, routes) {
    state.routes = constantRoutes.concat(routes,anyRoutes)

    // 添加路由规则
    router.addRoutes(state.routes)
  }
}

const actions = {
  // user login    使用async/await 改写.then().catch()
  async login({ commit }, userInfo) {
    const { username, password } = userInfo

    try {
      const response = await login({ username: username.trim(), password: password })
      const { data } = response
      commit('SET_TOKEN', data.token)
      setToken(data.token)
    } catch (error) {
      return Promise.reject(error)
    }
  },

  // get user info    使用async/await 改写.then().catch()
  async getInfo({ commit, state }) {

    try {
      const response = await getInfo(state.token)
      const { data } = response
      if (!data) {
        return Promise.reject('Verification failed, please Login again.')
      }
      const { name, avatar } = data

      commit('SET_USERINFO', { name, avatar })

      // 设置异步路由
      commit('SET_ASYNCROUTES', filterAsyncRoutes(data.routes, asyncRoutes))
      return data
    } catch (error) {
      return Promise.reject(error)
    }
  },

  // user logout    使用async/await 改写.then().catch()
  async logout({ commit, state }) {
    try {
      await logout(state.token)
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
    } catch (error) {
      return Promise.reject(error)
    }
  },

  // remove token    使用async改写
  async resetToken({ commit }) {
    removeToken() // must remove  token  first
    commit('RESET_STATE')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

